package com.aabte.nettyleran.netty.http.xml.httpencoder;

import com.aabte.nettyleran.netty.http.xml.entity.Order;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.JiBXException;

import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/14
 */
public abstract class AbstractHttpXmlEncoder<T> extends MessageToMessageEncoder<T> {

    protected IBindingFactory factory;
    protected StringWriter writer;
    protected static final Charset UTF_8 = StandardCharsets.UTF_8;
    protected static final String CHARSET_NAME = UTF_8.toString();

    /**
     * 将Order对象转换成bytes
     *
     * @param ctx
     * @param body Order对象
     * @return
     * @throws JiBXException
     * @throws IOException
     */
    protected ByteBuf encode0(ChannelHandlerContext ctx, Order body) throws JiBXException, IOException {
        factory = BindingDirectory.getFactory(body.getClass());
        writer = new StringWriter();
        IMarshallingContext mctx = factory.createMarshallingContext();
        mctx.setIndent(2);
        mctx.marshalDocument(body, CHARSET_NAME, null, writer);
        String xmlBody = writer.toString();
        writer.close();
        writer = null;
        return Unpooled.copiedBuffer(xmlBody, UTF_8);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        if (writer != null) {
            writer.close();
        }
        ctx.close();
    }
}
